package com.yanqu.road.dao.impl.servercenter;

import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.impl.TempDao;

import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SystemSwitchDaoImpl extends TempDao {
    public List<Integer> getLockSystemIdList(long serverId) throws Exception {
        String sql = "select systemId from t_s_system_server_status where serverId = ? and status = 0";
        ResultSet rs = null;
        CallableStatement call = null;
        List<Integer> list = new ArrayList<>();
        try {
            getDb().setConnName(DbNameStrategy.getServerDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setLong(1, serverId);
            rs = call.executeQuery();
            while (rs.next()) {
                list.add(rs.getInt("systemId"));
            }
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
            throw e;
        } finally {
            getDb().closeConnection(call, rs);
        }
        return list;
    }

    public Map<Long, List<Integer>> getLockSystemIdList() throws Exception {
        Map<Long, List<Integer>> map = new ConcurrentHashMap<>();
        String sql = "select serverId,systemId from t_s_system_server_status where status = 0";
        ResultSet rs = null;
        CallableStatement call = null;
        try {
            getDb().setConnName(DbNameStrategy.getServerDb());
            call = getDb().getConnection().prepareCall(sql);
            rs = call.executeQuery();
            while (rs.next()) {
                long serverId = rs.getLong("serverId");
                List<Integer> list = map.getOrDefault(serverId, new ArrayList<>());
                list.add(rs.getInt("systemId"));
                map.put(serverId, list);
            }
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
            throw e;
        } finally {
            getDb().closeConnection(call, rs);
        }
        return map;
    }
}
